package com.tabbinder.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Label;

public class ListItem extends Label {
	private JSONObject json;

	/** Create a new list item from the given JSON object */
	public ListItem(final MasterBind master, JSONObject item) {
		this.json = item;
		this.addStyleName("binderListItem");
		// Don't even bother checking what is String and what is Number.
		// Just call toString() - they are all scalars
		this.setText(getBinderTitle());
		if (getFavorite())
			this.addStyleName("favoriteBinder");

		this.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				master.itemSelected(ListItem.this);
			}
		});
	}

	public String getBinderTitle() {
		JSONString val = (JSONString) json.get("title");
		if (val == null)
			return "";
		return val.stringValue();
	}

	public void setBinderTitle(String text) {
		json.put("title", new JSONString(text));
		this.setText(text);
	}

	public boolean getFavorite() {
		JSONBoolean fav = (JSONBoolean) json.get("favorite");
		return (fav != null && fav.booleanValue());
	}

	public void setFavorite(Boolean value) {
		json.put("favorite", JSONBoolean.getInstance(value));
		if (value)
			this.addStyleName("favoriteBinder");
		else
			this.removeStyleName("favoriteBinder");
	}

	public int getRecordCount() {
		JSONNumber count = (JSONNumber) json.get("record_count");
		if (count == null)
			return 0;
		return (int) count.doubleValue();
	}

	public JSONObject getJson() {
		return json;
	}
	
	public JSONValue getId() {
		return json.get("id");
	}
}
